using Google.ProtocolBuffers;
using micromsg;
using MicroMsg.Common.Event;
using MicroMsg.Common.Utils;
using MicroMsg.Manager;
using MicroMsg.Protocol;
using MicroMsg.Storage;
using Microsoft.Phone.Info;
using System;
namespace MicroMsg.Network
{
	public class AuthPack
	{
		public static SessionPack makeAutoAuthPack(int scene)
		{
			AuthRequest authRequest = AuthPack.makeAuthRequest(scene);
			if (authRequest == null)
			{
				return null;
			}
			SessionPack sessionPack = new SessionPack();
			sessionPack.mCmdID = 1;
			sessionPack.mRequestObject = authRequest;
			sessionPack.mProcRequestToByteArray += new RequestToByteArrayDelegate(AuthPack.authRequestToByteArray);
			sessionPack.mCompleted += new SessionPackCompletedDelegate(AuthPack.onAutoAuthCompleted);
			return sessionPack;
		}
		private static void onAutoAuthCompleted(object sender, PackEventArgs e)
		{
			if (!e.isSuccess())
			{
				Log.smethod_1("Network", "auto auth failed .");
				return;
			}
			SessionPack sessionPack = sender as SessionPack;
			AuthResponse authResponse = (AuthResponse)sessionPack.mResponseObject;
			RetConst ret = (RetConst)authResponse.BaseResponse.Ret;
			if (ret != RetConst.MM_OK && ret != RetConst.MM_ERR_CRITICALUPDATE)
			{
				if (ret != RetConst.MM_ERR_RECOMMENDEDUPDATE)
				{
					if (ret != RetConst.MM_ERR_NEED_VERIFY)
					{
						Log.smethod_1("Network", "auto auth failed, result = " + ret);
						EventCenter.postEvent(EventConst.ON_NETSCENE_AUTOAUTH_ERR, ret, null);
						return;
					}
					if (authResponse.ImgBuf != null && authResponse.ImgSid != null)
					{
						VerifyCodeArgs verifyCodeArgs = new VerifyCodeArgs();
						verifyCodeArgs.mImageSid = authResponse.ImgSid.String;
						verifyCodeArgs.mImageBuf = authResponse.ImgBuf.Buffer.ToByteArray();
						Log.smethod_1("Network", "auto auth failed, need verify,  sid = " + verifyCodeArgs.mImageSid);
						EventCenter.postEvent(EventConst.ON_NETSCENE_AUTH_NEEDVERIFY, verifyCodeArgs, null);
						return;
					}
					Log.smethod_1("Network", "NEED_VERIFY_USER, but ImgSid or ImgBuf is null");
					EventCenter.postEvent(EventConst.ON_NETSCENE_AUTOAUTH_ERR, ret, null);
					return;
				}
			}
			Log.smethod_4("Network", "auto auth success. ");
			Account curAccount = AccountMgr.getCurAccount();
			curAccount.bytesSessionkey = authResponse.SessionKey.ToByteArray();
			curAccount.nUin = authResponse.Uin;
			curAccount.dbLastSessionKeyTimeStamp = Util.getNowSeconds();
			curAccount.bytesA2Key = authResponse.A2Key.Buffer.ToByteArray();
			AccountMgr.updateAccount();
			EventCenter.postEvent(EventConst.ON_NETSCENE_AUTOAUTH_SUCCESS, authResponse, null);
		}
		public static void updateAccountInfoFromReg(object request)
		{
			RegRequest regRequest = request as RegRequest;
			SessionPackMgr.getAccount().setAuthInfo(regRequest.UserName.String, regRequest.Pwd.String, regRequest.Pwd2);
		}
		public static void updateAccountInfoFromNewReg(object request)
		{
			NewRegRequest newRegRequest = request as NewRegRequest;
			SessionPackMgr.getAccount().setAuthInfo(newRegRequest.UserName, newRegRequest.Pwd, "");
		}
		public static void updateAccountInfoFromAuth(object request)
		{
			AuthRequest authRequest = request as AuthRequest;
			SessionPackMgr.getAccount().setAuthInfo(authRequest.UserName.String, authRequest.Pwd.String, authRequest.Pwd2);
		}
		private static AuthRequest makeAuthRequest(int scene)
		{
			if (!SessionPackMgr.getAccount().isValid())
			{
				return null;
			}
			BaseRequest baseRequest = BaseRequest.DefaultInstance;
			BaseRequest.Builder builder = BaseRequest.CreateBuilder();
			builder.SessionKey = ByteString.CopyFrom(SessionPackMgr.getSessionKeyEx());
			builder.Uin = (uint)SessionPackMgr.getAccount().getUin();
			builder.DeviceID = ByteString.CopyFromUtf8(Util.getDeviceUniqueId());
			builder.ClientVersion = (int)ConstantsProtocol.CLIENT_VERSION;
			builder.DeviceType = ByteString.CopyFrom(Util.toFixLenString(ConstantsProtocol.DEVICE_TYPE, 132));
			builder.Scene = (uint)scene;
			baseRequest = builder.Build();
			AuthRequest arg_82_0 = AuthRequest.DefaultInstance;
			AuthRequest.Builder builder2 = AuthRequest.CreateBuilder();
			builder2.BaseRequest = baseRequest;
			builder2.UserName = Util.toSKString(SessionPackMgr.getAccount().getUsername());
			builder2.Pwd = Util.toSKString(SessionPackMgr.getAccount().getPassword());
			builder2.ImgSid = Util.toSKString("");
			builder2.ImgCode = Util.toSKString("");
			builder2.Channel = AppInfoHelper.ChannelId;
			builder2.Language = AccountMgr.GetCurrentLanguage();
			builder2.DeviceBrand = DeviceStatus.get_DeviceManufacturer();
			builder2.DeviceModel = DeviceStatus.get_DeviceName();
			builder2.OSType = Environment.get_OSVersion().get_Version().ToString();
			builder2.TimeZone = Util.getTimeZoneOffsetGwt();
			return builder2.Build();
		}
		private static byte[] authRequestToByteArray(object object_0)
		{
			AuthRequest authRequest = object_0 as AuthRequest;
			return authRequest.ToByteArray();
		}
		public static object onParserAuthPack(SessionPack sessionPack)
		{
			AuthResponse authResponse = AuthResponse.ParseFrom(sessionPack.mResponseBuffer);
			if (authResponse == null)
			{
				Log.smethod_1("Network", "auth parse failed. ");
				return null;
			}
			int uin = (int)authResponse.Uin;
			RetConst ret = (RetConst)authResponse.BaseResponse.Ret;
			Log.smethod_5("Network", "auth parsed success. ");
			if (uin != 0 && (ret == RetConst.MM_OK || ret == RetConst.MM_ERR_CRITICALUPDATE || ret == RetConst.MM_ERR_RECOMMENDEDUPDATE))
			{
				Log.smethod_4("Network", "auth PASS, uin= " + uin);
				AuthRequest authRequest = sessionPack.mRequestObject as AuthRequest;
				if (authRequest != null && authRequest.UserName.String == "facebook@wechat_auth")
				{
					SessionPackMgr.getAccount().setAuthInfo(authResponse.UserName.String, authResponse.Password, authResponse.Password);
				}
				SessionPackMgr.setSessionKey(authResponse.SessionKey.ToByteArray());
				SessionPackMgr.getAccount().setUin(uin);
				SessionPackMgr.setAuthStatus(2);
				return authResponse;
			}
			Log.smethod_1("Network", "auth Failed,ret = " + ret);
			if (ret == RetConst.MM_ERR_NEEDREG)
			{
				Log.smethod_4("Network", "auth result: need register");
				SessionPackMgr.mAuthTicket1 = authResponse.Ticket;
				Connector.close();
				return authResponse;
			}
			SessionPackMgr.setSessionKey(null);
			SessionPackMgr.getAccount().reset();
			RetConst retConst = ret;
			if (retConst != RetConst.MM_ERR_AUTH_ANOTHERPLACE)
			{
				switch (retConst)
				{
				case RetConst.MM_ERR_RECOMMENDEDUPDATE:
					Log.smethod_1("Network", "Auth Failed: MM_ERR_RECOMMENDEDUPDATE ");
					break;
				case RetConst.MM_ERR_CRITICALUPDATE:
					Log.smethod_1("Network", "Auth Failed: MM_ERR_CRITICALUPDATE ");
					break;
				default:
					switch (retConst)
					{
					case RetConst.MM_ERR_NEED_VERIFY:
						Log.smethod_1("Network", "Auth Failed: MM_ERR_NEED_VERIFY ");
						break;
					case RetConst.MM_ERR_NOUSER:
						Log.smethod_1("Network", "Auth Failed: MM_ERR_NOUSER ");
						break;
					case RetConst.MM_ERR_PASSWORD:
						Log.smethod_1("Network", "Auth Failed: MM_ERR_PASSWORD ");
						break;
					}
					break;
				}
			}
			else
			{
				Log.smethod_1("Network", "Auth Failed: MM_ERR_AUTH_ANOTHERPLACE ");
				Sender.getInstance().closeSender();
			}
			Connector.close();
			return authResponse;
		}
		public static object onParserNewRegPack(SessionPack sessionPack)
		{
			NewRegResponse newRegResponse = NewRegResponse.ParseFrom(sessionPack.mResponseBuffer);
			if (newRegResponse == null)
			{
				Log.smethod_1("Network", "new reg parse failed. ");
				return null;
			}
			int uin = (int)newRegResponse.Uin;
			RetConst ret = (RetConst)newRegResponse.BaseResponse.Ret;
			Log.smethod_5("Network", string.Concat(new object[]
			{
				"new reg parsed success. uin= ",
				uin,
				"ret =",
				ret
			}));
			NewRegRequest newRegRequest = sessionPack.mRequestObject as NewRegRequest;
			uint arg_80_0 = newRegRequest.RegMode;
			if (uin != 0 && ret == RetConst.MM_OK)
			{
				Log.smethod_4("Network", "new reg PASS");
				SessionPackMgr.setSessionKey(Util.StringToByteArray(newRegResponse.SessionKey));
				SessionPackMgr.getAccount().setUin(uin);
				SessionPackMgr.setAuthStatus(2);
				return newRegResponse;
			}
			Log.smethod_1("Network", "new reg failed, ret = " + ret);
			SessionPackMgr.setSessionKey(null);
			SessionPackMgr.getAccount().reset();
			return newRegResponse;
		}
		public static object onParserRegPack(SessionPack sessionPack)
		{
			RegResponse regResponse = RegResponse.ParseFrom(sessionPack.mResponseBuffer);
			if (regResponse == null)
			{
				Log.smethod_1("Network", "register parse failed. ");
				return null;
			}
			Log.smethod_5("Network", "register parsed success. ");
			int uin = (int)regResponse.Uin;
			RetConst ret = (RetConst)regResponse.BaseResponse.Ret;
			if (uin != 0 && ret == RetConst.MM_OK)
			{
				Log.smethod_4("Network", "register PASS");
				SessionPackMgr.setSessionKey(regResponse.SessionKey.ToByteArray());
				SessionPackMgr.getAccount().setUin(uin);
				SessionPackMgr.setAuthStatus(2);
				return regResponse;
			}
			Log.smethod_1("Network", "register Failed, ret = " + ret);
			SessionPackMgr.setSessionKey(null);
			SessionPackMgr.getAccount().reset();
			return regResponse;
		}
		public static object onParserGetUserNamePack(SessionPack sessionPack)
		{
			GetUserNameResponse getUserNameResponse = GetUserNameResponse.ParseFrom(sessionPack.mResponseBuffer);
			if (getUserNameResponse == null)
			{
				Log.smethod_1("Network", "getusername parse failed. ");
				return null;
			}
			Connector.close();
			Log.smethod_5("Network", "getUserName parsed success. ");
			RetConst ret = (RetConst)getUserNameResponse.BaseResponse.Ret;
			if (ret != RetConst.MM_OK)
			{
				Log.smethod_1("Network", "NetSceneGetUserName: failed. ret = " + ret);
				return getUserNameResponse;
			}
			Log.smethod_4("Network", "NetSceneGetUserName: success.name = " + getUserNameResponse.UserName);
			SessionPackMgr.getAccount().setUsername(getUserNameResponse.UserName);
			SessionPackMgr.mAuthTicket2 = getUserNameResponse.Ticket;
			return getUserNameResponse;
		}
		public static bool preProcessAuthPack(SessionPack sessionPack, ref object responseObject)
		{
			int mCmdID = sessionPack.mCmdID;
			if (mCmdID == 1)
			{
				responseObject = AuthPack.onParserAuthPack(sessionPack);
				return responseObject != null;
			}
			switch (mCmdID)
			{
			case 31:
				responseObject = AuthPack.onParserRegPack(sessionPack);
				return responseObject != null;
			case 32:
				responseObject = AuthPack.onParserNewRegPack(sessionPack);
				return responseObject != null;
			case 33:
				responseObject = AuthPack.onParserGetUserNamePack(sessionPack);
				return responseObject != null;
			default:
				return true;
			}
		}
	}
}
